import axios from "axios";
import store from "@/store";
import qs from 'query-string';
import CryptoJS from 'crypto-js'

axios.defaults.headers.common["Content-Type"] = "application/json;";


const myAxios = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 5000,
});

myAxios.interceptors.request.use(
  config => {
    const urlHash = location.hash  // ?name=jim
    // const urlSearch = urlHash.search  // ?name=jim
    const paramsStr = urlHash.replace('#/holdingPeriodReturnCalc', '')

    const urlParams = qs.parse(paramsStr) || {};

    const getToken = urlParams.token || "989e7794-dbfd-42e9-a351-895d4d3565b3";
    const Timestamp = new Date().getTime()
    const hash = CryptoJS.HmacSHA256(Timestamp + "", getToken).toString()

    // 为请求头挂载 Authorization 字段
    // if (store.state.token) {
    //   config.headers.Authorization = store.state.token;
    // }

    // axios.defaults.headers.common['Authorization'] = `bearer ${getToken}`
    // axios.defaults.headers.common["Content-Type"] = "application/json;";
    // axios.defaults.headers.common["Signature"] = hash;
    // axios.defaults.headers.common["Timestamp"] = Timestamp;

    config.headers.Authorization = `Bearer ${getToken}`;
    config.headers.Signature = hash;
    config.headers.Timestamp = Timestamp;
    return config;
  },
  error => Promise.reject(error)
);

myAxios.interceptors.response.use(response => {
  return response
}, error => {

  if (error.response.status === 401) {
    store.commit('updateToken', '')
    router.push("/login");
  }

  return Promise.reject(error)
})

export default myAxios